package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.base.staticdata.ServiceOfferConst;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneAccessProdInstService;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneGiftOfferInstService;
import com.iwhalecloud.bss.kite.client.dto.inst.OfferInstDTO;
import com.iwhalecloud.bss.kite.client.dto.inst.ProdInstDTO;
import com.iwhalecloud.bss.kite.client.dto.spec.OfferDetailDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdRoleModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProductModuleVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccOfferInstVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.spec.impl.transfer.GoodsInfoTransfer;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.DirtyDataWrapper;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;

/**
 * <Description> <br>
 * 套餐组件处理类
 *
 * @author zhu.zixin<br>
 * @version 1.0<br>
 * @since R9.0<br>
 */
@Service
public class LocalOfferModuleHandler extends LocalAbstractProductModuleHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IQuerySceneAccessProdInstService querySceneProdInstService;

    @Autowired
    private IQuerySceneGiftOfferInstService querySceneGiftOfferInstService;

    @Override
    public List<ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {

        // 1.获取销售品规格信息
        Offer offer = OfferCache.get(context.getAcceptRequest().getOfferId());
        if (Objects.isNull(offer)) {
            ErrorConsts.OFFER_NOT_FOUND.throwOut();
        }

        // 2.初始销售品页面对象
        CuccOfferInstVO offerInstVO = this.genOfferInstVO(offer);
        List<ProductModuleVO> productModuleList = this.getProdInstModuleVO(context, context.getAcceptRequest().getCustId(), context.getAcceptRequest().getOfferInstId());
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(context.getSceneVo().getSceneInstId());
        //融合产品变更时主产品属性不可编辑
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(context.getAcceptRequest().getCustId(), sceneInst.getRootInstId());
        //String objId = OfferCache.get(offerInst.geta).getAttrValue("cateId");
        String cateId = offerInst.getAttrValue("cateId");
        if (KiteStringUtils.equalsAny(cateId, DcPublicCache.getCodeb("210728701", "wlwCate").split(","))
            &&Objects.equals(InstType.GIFT_OFFER_INST, sceneInst.getRootInstType())&&KiteStringUtils.isNotEmpty(sceneInst.getServiceOfferId())
            &&KiteStringUtils.equals(ServiceOfferConst.service_offer_2826,sceneInst.getServiceOfferId())){
            productModuleList.forEach(productModuleVO->{
                productModuleVO.getProdRole().forEach(prodRole ->{
                    prodRole.getProdAttr().getProdAttrList().forEach(prodAttr ->{
                        prodAttr.setIsEdit(KeyConsts.IFTRUE_F);
                        if (KiteStringUtils.isEqual(prodAttr.getIsEditImg(), KeyConsts.IFTRUE_T)) {
                            prodAttr.setIsEditImg(KeyConsts.IFTRUE_F);
                        }
                    });
                });
            });
        }
        // 追加配件不展示框架产品
        if (!KiteStringUtils.isEqual("2020", context.getAcceptRequest().getServiceOfferId())) {
            offerInstVO.setProduct(productModuleList);
        }
        // 3.通过对象管理器获取销售品实例
        offerInstVO.setOfferInstId(context.getAcceptRequest().getOfferInstId());

        // 4. 组装套餐组件页面对象
        ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getOffer().getOfferInstList()
            .add(offerInstVO);
        // 对产品属性进行分组
        divideProdAttr(productModuleList, context.getAcceptRequest().getSceneInstId(),
            context.getAcceptRequest().getCustId(), false);
        // 5.设置当前组件页面对象
        return Collections
            .singletonList(((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getOffer());
    }

    @Override
    public List<? extends ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        // 1.获取销售品规格信息
        Offer offer = OfferCache.get(context.getAcceptRequest().getOfferId());
        if (Objects.isNull(offer)) {
            ErrorConsts.OFFER_NOT_FOUND.throwOut();
        }

        // 2.初始销售品页面对象
        CuccOfferInstVO offerInstVO = this.genOfferInstVO(offer);
        List<ProductModuleVO> productModuleList = this.getProdInstModuleVO(context, context.getAcceptRequest().getCustId(), context.getAcceptRequest().getOfferInstId());
        if (KiteListUtils.isEmpty(productModuleList)) {
            return productModuleList;
        }

        for (ProductModuleVO product : productModuleList) {
            List<ProdRoleModuleVO> prodRoleModuleList = product.getProdRole();
            if (KiteListUtils.isEmpty(prodRoleModuleList)) {
                continue;
            }
            product.setIsEdit(LocalKeyConsts.IFTRUE_F);
            for (ProdRoleModuleVO prodRoleModule : prodRoleModuleList) {
                ProdAttrModuleVO prodAttrModule = prodRoleModule.getProdAttr();
                List<ProdAttrVO> prodAttrList = prodAttrModule.getProdAttrList();
                Iterator<ProdAttrVO> iterator = prodAttrList.iterator();
                while (iterator.hasNext()) {
                    ProdAttrVO prodAttr = iterator.next();
                    if (KeyConsts.PROD_ATTR_SHOW_TYPE_E.equals(prodAttr.getShowType())) {
                        // 过滤隐藏的产品属性
                        iterator.remove();
                    }
                    else {
                        prodAttr.setAttrValueTypeId(LocalKeyConsts.ATTRVALUE_TT);
                    }
                }
            }
        }
        // 预览页面展示新旧值处理
        dealPreviewOldAndNewValues(productModuleList, context.getAcceptRequest().getSceneInstId());
        // 追加配件不展示框架产品
        if (!KiteStringUtils.isEqual("2020", context.getAcceptRequest().getServiceOfferId())) {
            offerInstVO.setProduct(productModuleList);
        }
        // 3.通过对象管理器获取销售品实例
        offerInstVO.setOfferInstId(context.getAcceptRequest().getOfferInstId());

        // 4. 组装套餐组件页面对象
        ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getOffer().getOfferInstList()
            .add(offerInstVO);
        // 对产品属性进行分组
        divideProdAttr(productModuleList, context.getAcceptRequest().getSceneInstId(),
            context.getAcceptRequest().getCustId(), false);
        // 5.设置当前组件页面对象
        return Collections
            .singletonList(((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getOffer());
    }

    private CuccOfferInstVO genOfferInstVO(Offer offer) {
        CuccOfferInstVO offerInstVO = new CuccOfferInstVO();
        offerInstVO.setOfferId(offer.getOfferId());
        offerInstVO.setOfferName(offer.getOfferName());
        offerInstVO.setOfferSysType(offer.getOfferSysType());
        offerInstVO.setOfferType(offer.getOfferType());
        offerInstVO.setOfferDesc(offer.getOfferDesc());
        return offerInstVO;
    }

    @Override
    public List<? extends ModuleVO> refresh(AcceptContext context, SceneModule sceneModule,
        DirtyDataWrapper dirtyDataWrapper) {
        if (!KiteObjectUtils.isEmpty(context) && !KiteObjectUtils.isEmpty(context.getSceneVo()) && !KiteObjectUtils
            .isEmpty(((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO()) && !KiteObjectUtils
            .isEmpty(((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getOffer())) {
            return Collections
                .singletonList(((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getOffer());
        }
        return new ArrayList<>();
    }

    private List<ProductModuleVO> getProdInstModuleVO(AcceptContext context, String custId, String offerInstId) {
        String rootInstId = querySceneInstService.getSceneInst(context.getAcceptRequest().getSceneInstId()).getRootInstId();
        String offerId = querySceneInstService.getOfferInst(custId, rootInstId).getSpecId();
        Offer offer = OfferCache.get(offerId);
        if (Objects.isNull(offer)) {
            ErrorConsts.OFFER_NOT_FOUND.throwOut();
        }

        List<KiteProdInst> prodInstList = querySceneInstService.listProdInstsFromOfferInst(custId, rootInstId);
        List<String> prodInstIds=  prodInstList.stream().map(KiteProdInst::getProdInstId).collect(Collectors.toList());

        //查询这个offer下有效的接入产品
        List<ProdInstDTO> prodInstDtoList = querySceneProdInstService
            .listEffProdInsts(context.getAcceptRequest().getSceneInstId(), context.getAcceptRequest().getCustId())
            .getResultObject();

        prodInstDtoList = prodInstDtoList.stream()
            .filter((prodInst) -> (KeyConsts.PROD_FUNC_TYPE_101.equals(prodInst.getProdFuncType()) && prodInstIds.contains(prodInst.getProdInstId())))
            .collect(Collectors.toList());
        //offer是套餐或者促销
        if (StringUtils.equalsAny(offer.getOfferType(), KeyConsts.OFFER_TYPE_15)) {
            //获取场景中有效的主套餐
            List<OfferInstDTO> offerInstList = querySceneGiftOfferInstService.getGiftOfferInstList(context.getAcceptRequest().getSceneInstId()).getResultObject();
            //去除附加产品
            offerInstList
                .removeIf(dto -> GoodsInfoTransfer.isAddRoleOffer(dto.getOfferId(), OfferCache.get(dto.getOfferId()).getCateId()));
            List<OfferDetailDTO> offerDetails = new ArrayList<>();
            for (OfferInstDTO offerInst : offerInstList) {

                offerDetails.addAll(KiteBeanUtils
                    .copyPropsForList(OfferCache.get(offerInst.getOfferId()).listAccessProdDetail(),
                        OfferDetailDTO.class));
            }
            //加载场景中所有主套餐下的产品
            return getProdModuleVO(offerDetails, prodInstDtoList, context);
        }
        return Lists.newArrayList();
    }
}
